package com.spring.springboot.sys.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.spring.springboot.service.ConfigService;
import com.spring.springboot.sys.core.constant.BusinessConstant;
import com.spring.springboot.sys.core.model.ConfigInitInfo;
import com.spring.springboot.sys.core.model.Result;
import com.spring.springboot.sys.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 宋义州
 * @date 2022-07-25  23:12
 * @description 系统缓存管理
 */
@Slf4j
@Api(tags = "缓存处理")
@RestController
@RequestMapping("/api/cache")
public class CacheController {

    @Resource
    private ConfigService configService;

    @Resource
    private RedisUtils redisUtils;

    @PutMapping("refreshSystemCache")
    @ApiOperation(value = "刷新系统参数")
    @Operation(security = {@SecurityRequirement(name = "Authorization")})
    public Result refreshSystemCache() {
        log.info("------：{}:{}", "开始刷新系统参数至redis缓存", LocalDateTime.now().format(DateTimeFormatter.ofPattern(BusinessConstant.DateFormat.DATE_TIME_FORMAT)));
        try {
            //查询系统参数
            List<ConfigInitInfo> configInitInfos = configService.selectListWithRedisCache();
            if (CollectionUtil.isNotEmpty(configInitInfos)) {
                for (ConfigInitInfo info : configInitInfos) {
                    redisUtils.set(info.getCode(), info.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        log.info("------:{}:{}", "刷新系统参数至redis缓存完成", LocalDateTime.now().format(DateTimeFormatter.ofPattern(BusinessConstant.DateFormat.DATE_TIME_FORMAT)));
        return Result.success("系统参数刷新完成！");
    }

}
